<script setup lang="ts">
import type {
  SysDeptQo,
  SysDeptTreeVo,
} from '#/system/dept'
import type {
  SysUserVo,
} from '#/system/user'
import {
  createSysDeptApi,
  getSysDeptDetailsApi,
  getSysDeptTreeApi,
  updateSysDeptApi,
} from '@/api/system/dept'

interface OnCloseResolveType extends CloseResolveType {}
let onCloseResolve = function (_value: OnCloseResolveType) { }

const dialogRef = $ref<DialogInstance>()
const ruleFormRef = ref<FormInstance>()
let deptTree = $ref<SysDeptTreeVo[]>([])
let dialogModal = $ref<SysDeptQo>({})
let dialogAction = $ref<DialogAction>('add')
let confirmLoading = $ref(false)
let dialogLoading = $ref(false)
let pid = $ref<string>()
let userList = $ref<SysUserVo[]>([])

const rules = reactive<FormRules<SysDeptQo>>({
  name: [
    { required: true, message: '请输入机构名称', trigger: 'blur' },
  ],
  leaderUserIds: [
    { required: true, message: '请选择负责人', trigger: 'blur' },
  ],
})

async function getDefaultModel() {
  return {
    deptType: 1,
    deptRank: 1,
  } as SysDeptQo
}
// 打开
async function showDialog(args: {
  title: string
  action?: DialogAction
  model: {
    id?: string
  }
  userList: SysUserVo[]
}) {
  const dialogRes = dialogRef!.openDialog<OnCloseResolveType>({
    title: args.title,
  })

  ruleFormRef.value?.clearValidate()
  onCloseResolve = dialogRes.onCloseResolve

  dialogAction = args.action ?? 'add'
  userList = args.userList

  if (args.model.id) {
    dialogModal.id = args.model.id
  }

  if (args.action === 'add') {
    const defaultModel = await getDefaultModel()
    dialogModal = {
      ...defaultModel,
      pid: args.model.id,
    }
    pid = args.model.id
  }
  else if (args.action === 'edit' || args.action === 'views') {
    await reflash()
  }
  await getSelectList()

  return await dialogRes.dialogPrm
}

async function reflash() {
  if (!dialogModal.id)
    return
  dialogLoading = true
  pid = ''
  const res = await getSysDeptDetailsApi(dialogModal.id)
  if (!res)
    return
  dialogLoading = false
  Object.assign(dialogModal, res.data)
  if (res.data.pid !== '0') {
    pid = res.data.pid
  }
}

async function getSelectList() {
  deptTree = (await getSysDeptTreeApi()).data
}

// 确认
async function confirm(formEl: FormInstance | undefined) {
  if (!formEl)
    return
  await formEl.validate(async (valid) => {
    if (!valid) {
      return
    }
    confirmLoading = true
    if (dialogAction === 'add') {
      await createSysDeptApi(dialogModal).finally(() => {
        confirmLoading = false
      })
    }
    else if (dialogAction === 'edit') {
      await updateSysDeptApi(dialogModal).finally(() => {
        confirmLoading = false
      })
    }
    confirmLoading = false
    Message({
      type: 'success',
      message: `${DialogActionMap[dialogAction as DialogAction]}成功`,
    })
    onCloseResolve({ type: true })
  })
}

// 取消
function cancel() {
  ruleFormRef.value?.clearValidate()
  onCloseResolve({ type: false })
}

defineExpose({ showDialog })
</script>

<template>
  <sy-dialog
    ref="dialogRef"
    :before-close="cancel"
    :hide-confirm="dialogAction === 'views'"
    :confirm-loading="confirmLoading"
    :disabled-confirm="dialogLoading"
    @confirm="confirm(ruleFormRef)"
  >
    <el-form
      ref="ruleFormRef"
      v-loading="dialogLoading"
      :model="dialogModal"
      :rules="rules"
      label-width="auto"
      status-icon
    >
      <el-form-item
        label="机构类型"
        prop="deptType"
      >
        <sy-dict
          v-model="dialogModal.deptType"
          dict-type="dept_type"
          type="segmented"
        />
      </el-form-item>
      <el-form-item label="上级机构" prop="pid">
        <el-tree-select
          v-model="pid"
          :data="deptTree"
          node-key="id"
          :render-after-expand="false"
          check-strictly
          :props="{
            label: 'name',
          }"
          @change="() => {
            dialogModal.pid = pid
          }"
        />
      </el-form-item>
      <el-form-item label="机构编码" prop="code">
        <el-input
          v-model="dialogModal.code"
          placeholder="请输入机构编码"
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
      <el-form-item label="机构名称" prop="name">
        <el-input
          v-model="dialogModal.name"
          placeholder="请输入机构名称"
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
      <el-form-item label="机构排序" prop="deptRank">
        <el-input
          v-model="dialogModal.deptRank"
          placeholder="请输入机构排序值"
          :disabled="dialogAction === 'views'"
          type="number"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="leaderUserIds">
        <el-select
          v-model="dialogModal.leaderUserIds"
          multiple
          :disabled="dialogAction === 'views'"
          style="width: 100%;"
          placeholder="请选择负责人"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </sy-dialog>
</template>

<style scoped></style>
